package com.hjq.mallsearch.impl;

import com.alibaba.fastjson.JSON;
import com.hjq.common.entity.es.SkuEsModel;
import com.hjq.mallsearch.config.MallElasticSearchConfig;
import com.hjq.mallsearch.constant.EsConstants;
import com.hjq.mallsearch.service.ProductUpService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @auther HJQ
 */
@Service
@Slf4j
public class ProducrUpServiceImpl implements ProductUpService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        //发送到Es

        //1.建立product的索引(kibana中已经建立了)
        //2.批量保存
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel:skuEsModels){
            //新建插入请求
            IndexRequest indexRequest = new IndexRequest(EsConstants.PRODUCT_INDEX);
            //指定id
            String id = skuEsModel.getSkuId().toString();
            indexRequest.id(id);
            String toJSON = JSON.toJSONString(skuEsModel);
            indexRequest.source(toJSON, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse itemResponses = restHighLevelClient.bulk(bulkRequest, MallElasticSearchConfig.REQUEST_OPTION);
        //TODO 错误处理
        if(itemResponses.hasFailures()){

            log.error("商品上架发送错误");
            return itemResponses.hasFailures();
        }
        return  true;

    }
}
